package com.tsx.template.service.impl;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;
import com.tsx.template.entity.AuthPermission;
import com.tsx.template.entity.AuthRole;
import com.tsx.template.mapper.AuthPermissionMapper;
import com.tsx.template.mapper.AuthRoleMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
@RequiredArgsConstructor
public class StpInterfaceImpl implements StpInterface {
    final AuthPermissionMapper authPermissionMapper;
    final AuthRoleMapper authRoleMapper;

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        log.info("用户id:{}", loginId);
        // 获取用户对应的session,其中包含redis中缓存的数据
        SaSession saSession = StpUtil.getSessionByLoginId(loginId);
        return saSession.get("permissions", () -> {
                    List<String> permissionList = getPermissionList(Long.parseLong(String.valueOf(loginId)));
                    saSession.set("permissions", permissionList);
                    return permissionList;
                }
        );
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        log.info("用户id:{}", loginId);
        SaSession saSession = StpUtil.getSessionByLoginId(loginId);
        return saSession.get("roles", () -> {
            List<String> roleList = getRoleList(Long.parseLong(String.valueOf(loginId)));
            saSession.set("roles", roleList);
            return roleList;
        });
    }

    // 获取权限code
    public List<String> getPermissionList(long loginId) {
        List<AuthPermission> permissions = authPermissionMapper.getPermissionsByUserId(loginId);
        log.info("用户权限code信息:{}", permissions);
        // 取出是对应的type是按钮级别的
        return permissions.stream().filter(p -> p.getType() == 1).map(AuthPermission::getCode).toList();
    }

    // 获取角色name
    public List<String> getRoleList(long loginId) {
        List<AuthRole> roles = authRoleMapper.getRolesByUserId(loginId);
        return roles.stream().map(AuthRole::getCode).toList();
    }
}
